package cn.dakaqi.web.api.common;

import cn.dakaqi.activity.services.ActivityService;
import cn.dakaqi.entities.*;
import cn.dakaqi.group.services.GroupService;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.user.service.UserService;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.utils.qiniu.QNiuToken;
import cn.dakaqi.utils.rongYun.ApiHttpClient;
import cn.dakaqi.utils.rongYun.models.FormatType;
import cn.dakaqi.web.api.v1.RongYunImController;
import cn.dakaqi.web.vo.MessageGroup;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.web.MediaTypes;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chunyang on 2016/4/18.
 * 七牛TOKEN获取
 */
@RestController
@RequestMapping(value = "/api/common")
@Slf4j
public class QiNiuRestController
{
    @Resource
    private UserService userService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    ActivityService activityService;
    @Autowired
    GroupService groupService;


    @RequestMapping(value = "/qiniu/token", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> token()
    {
        JsonResult result = new JsonResult();
        try
        {
            String token = QNiuToken.token("dakaqi");
            result.setCode(JsonResult.CODE_SUCCESS);
            result.setMessage("获取成功");
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", token);
            result.setData(resultMap);
        } catch (Exception e)
        {
            result.setCode(JsonResult.CODE_FAIL);
            result.setMessage(e.getMessage());
            result.setData("");
        }
        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

    /**
     * 获取融云用户的TOKEN
     * @param memberCode
     * @return
     */
    @RequestMapping(value = "/rongYun/token/{memberCode}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<?> rongYunToken(@PathVariable("memberCode") String memberCode)
    {
        JsonResult result = new JsonResult();

        if (StringUtils.isBlank(memberCode) || "null".equals(memberCode.toLowerCase()))
        {
            String message = "用户不存在";
            log.warn(message);
            result.setMessage(message);
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }
        Volunteer volunteer = volunteerService.findByMemberCode(memberCode);
        log.info("查询编号为(" + memberCode + ")的用户信息");
        if (null == volunteer)
        {
            String message = "用户不存在";
            log.warn(message);
            result.setMessage(message);
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }
        if (volunteer == null)
        {
            String message = "用户不存在";
            log.warn(message);
            result.setMessage(message);
            result.setCode(JsonResult.CODE_FAIL);
            return new ResponseEntity<Object>(result, HttpStatus.OK);
        }

        UserOpenId userOpenId = userService.findOpenId(memberCode, 1);

        if (userOpenId == null)
        {
            try
            {
                String resultStr = ApiHttpClient.getToken(RongYunImController.KEY, RongYunImController.SECRET, memberCode, volunteer.getNickName(),
                        volunteer.getHeadUrl(), FormatType.json).getResult();

                JSONObject a = JSON.parseObject(resultStr);

                String token = a.getString("token");

                result.setCode(JsonResult.CODE_SUCCESS);
                result.setMessage("获取成功");
                Map<String, Object> resultMap = new HashMap<String, Object>();
                resultMap.put("token", token);
                result.setData(resultMap);

                UserOpenId saveOpenId = new UserOpenId();
                saveOpenId.setMemberCode(volunteer.getMemberCode());
                saveOpenId.setCreateTime(new Timestamp(new Date().getTime()));
                saveOpenId.setEffectiveTime(0);//default 0   anytime
                saveOpenId.setOpenId(token);
                saveOpenId.setType(1);
                userService.save(saveOpenId);

            } catch (Exception e)
            {
                result.setCode(JsonResult.CODE_FAIL);
                result.setMessage(e.getMessage());
                result.setData("");
            }
        } else
        {
            result.setCode(JsonResult.CODE_SUCCESS);
            result.setMessage("获取成功");
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("token", userOpenId.getOpenId());
            result.setData(resultMap);
        }

        return new ResponseEntity<Object>(result, HttpStatus.OK);
    }

    /**
     * 获取活动、社团群组信息
     * @param code
     * @return
     */
    @RequestMapping(value = "/rongYun/findMessageGroup/{code}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<JsonResult> findMessageGroup(@PathVariable("code") String code)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            System.out.println("code---------->" + code);
            MessageGroup messageGroup = new MessageGroup();
            String temp[] = code.split("\\|");
            if ("A".equals(temp[0]))
            {
                Activity activity = this.activityService.findByActivityCode(temp[1]);
                messageGroup.setCode(code);
                messageGroup.setName(activity.getName());
            }
            else
            {
                Group group = this.groupService.findByGroupCode(temp[1]);
                messageGroup.setCode(code);
                messageGroup.setName(group.getShortName());
            }
            jsonResult.setCode(0);
            jsonResult.setMessage("OK");
            jsonResult.setData(messageGroup);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

}
